import React, { useState } from 'react';
import { Button, Card, Col, Form, Input, message, Popconfirm, Row } from 'antd';
import { useAntdTable } from 'ahooks';
import Space from '@/components/Space';
import { GlobalFormLayout } from '@/layouts/Form';
import request from '@/utils/request';
import SlickTable from '@/components/SlickTable';
import useModal from '@/hooks/UseModal';
import IconLink from '@/components/IconLink';
import AddTenantModal from './AddTenantModal';

function fetchTenants({ current, pageSize, tenantName, tenantCode }) {
  return request.post('/tenant/page', {
    data: {
      current,
      pageSize,
      tenantName,
      tenantCode,
    },
  });
}

function TenantPage({ form, goToStep }) {
  const { getFieldDecorator, resetFields, getFieldsValue } = form;
  const { data, showModal, hideModal, visible } = useModal();
  const [mask, setMask] = useState(false);

  const {
    tableProps: { loading, ...restTableProps },
    refresh,
  } = useAntdTable(query => fetchTenants({ ...query, ...getFieldsValue() }), {
    defaultPageSize: 10,
  });

  const handleDeleteTenant = tenantId => {
    setMask(true);
    request
      .post(`/tenant/delete?tenantId=${tenantId}`)
      .then(() => {
        message.success('删除成功');
        refresh();
      })
      .finally(() => setMask(false));
  };

  const columns = [
    {
      title: '租户ID',
      dataIndex: 'tenantId',
    },
    {
      title: '租户名称',
      dataIndex: 'tenantName',
    },
    {
      title: '租户编码',
      dataIndex: 'tenantCode',
    },
    {
      title: 'HTTP数据源URL前缀',
      dataIndex: 'httpDataSourceUrlPrefix',
    },
    {
      title: '操作',
      render: (_, record) => (
        <Space divider="vertical">
          <IconLink icon="container" onClick={() => goToStep(2, { record })}>
            详情
          </IconLink>
          <IconLink icon="edit" onClick={() => showModal(record)}>
            编辑
          </IconLink>
          <Popconfirm
            title={`确定要删除租户【${record.tenantName}】吗`}
            onConfirm={() => handleDeleteTenant(record.tenantId)}
          >
            <IconLink className="text-danger" icon="delete">
              删除
            </IconLink>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <Card
      title="租户管理"
      className="cute"
      extra={
        <Button icon="usergroup-add" type="primary" onClick={showModal}>
          新增租户
        </Button>
      }
    >
      <Form className="margin-bottom" {...GlobalFormLayout}>
        <Row gutter={16}>
          <Col span={6}>
            <Form.Item label="租户名称">
              {getFieldDecorator('tenantName')(
                <Input onPressEnter={refresh} placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item label="租户编码">
              {getFieldDecorator('tenantCode')(
                <Input onPressEnter={refresh} placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col span={6}>
            <Space>
              <Button type="primary" onClick={refresh}>
                查询
              </Button>
              <Button type="default" onClick={() => resetFields()}>
                重置
              </Button>
            </Space>
          </Col>
        </Row>
      </Form>
      <SlickTable
        loading={mask || loading}
        rowKey="tenantId"
        columns={columns}
        {...restTableProps}
      />
      <AddTenantModal
        data={data}
        visible={visible}
        onCancel={() => {
          hideModal();
          refresh();
        }}
      />
    </Card>
  );
}

export default Form.create()(TenantPage);
